package org.ofbiz.steel.generate;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;

import org.apache.commons.io.FileUtils;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;

/**
 * File Utilities
 *
 */
public class SteelFileUtil {

    public static final String module = SteelFileUtil.class.getName();

    public static void writeString(String fileName, String s) throws IOException {
	writeString(null, fileName, s);
    }

    public static void writeString(String path, String name, String s) throws IOException {
	Writer out = getBufferedWriter(path, name);
	try { 
	    out.write(s + System.getProperty("line.separator"));
	} catch (IOException e) {
	    Debug.logError(e, module);
	    throw e;
	} finally {
	    if (out != null) {
		try {
		    out.close();
		} catch (IOException e) {
		    Debug.logError(e, module);
		}
	    }
	}
    }

    /**
     * Writes a file from a string with a specified encoding.
     *
     * @param path
     * @param name
     * @param encoding
     * @param s
     * @throws IOException
     */
    public static void writeString(String path, String name, String encoding, String s) throws IOException {
	String fileName = getPatchedFileName(path, name);
	if (UtilValidate.isEmpty(fileName)) {
	    throw new IOException("Cannot obtain buffered writer for an empty filename!");
	}

	try {
	    FileUtils.writeStringToFile(new File(fileName), s, encoding);
	} catch (IOException e) {
	    Debug.logError(e, module);
	    throw e;
	}
    }

    public static void writeString(String encoding, String s, File outFile) throws IOException {
	try {
	    FileUtils.writeStringToFile(outFile, s, encoding);
	} catch (IOException e) {
	    Debug.logError(e, module);
	    throw e;
	}
    }

    public static Writer getBufferedWriter(String path, String name) throws IOException {
	String fileName = getPatchedFileName(path, name);
	if (UtilValidate.isEmpty(fileName)) {
	    throw new IOException("Cannot obtain buffered writer for an empty filename!");
	}

	return new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8")));

	// return new BufferedWriter(new FileWriter(fileName));
    }

    public static String getPatchedFileName(String path, String fileName) throws IOException {
	// make sure the export directory exists
	if (UtilValidate.isNotEmpty(path)) {
	    path = path.replaceAll("\\\\", "/");
	    File parentDir = new File(path);
	    if (!parentDir.exists()) {
		parentDir.mkdirs();
//                if (!parentDir.mkdirs()) {
//                    throw new IOException("Cannot create directory for path: " + path);
//                }
	    }

	    // build the filename with the path
	    if (!path.endsWith("/")) {
		path = path + "/";
	    }
	    if (fileName.startsWith("/")) {
		fileName = fileName.substring(1);
	    }
	    fileName = path + fileName;
	}

	return fileName;
    }

    public static StringBuffer readTextFile(File file, boolean newline) throws FileNotFoundException, IOException {
	if (!file.exists()) {
	    throw new FileNotFoundException();
	}

	StringBuffer buf = new StringBuffer();
	BufferedReader in = null;
	try {
	    in = new BufferedReader(new FileReader(file));

	    String str;
	    while ((str = in.readLine()) != null) {
		buf.append(str);
		if (newline) {
		    buf.append(System.getProperty("line.separator"));
		}
	    }
	} catch (IOException e) {
	    Debug.logError(e, module);
	    throw e;
	} finally {
	    if (in != null) {
		try {
		    in.close();
		} catch (IOException e) {
		    Debug.logError(e, module);
		}
	    }
	}

	return buf;
    }

    public static StringBuffer readTextFile(String fileName, boolean newline)
	    throws FileNotFoundException, IOException {
	File file = new File(fileName);
	return readTextFile(file, newline);
    }

}
